/* eslint-disable @typescript-eslint/no-explicit-any */
type WhenContext = Record<string, any>;

type MenuItem = {
  id: string;
  label: string;
  disabled?: boolean;
  when?: (context: WhenContext) => boolean;
  whenDisabled?: (context: WhenContext) => boolean;
};

const menus = new Map<string, MenuItem[]>();

const MenuRegistry = {
  registry: (menuId: string, menuItem: MenuItem) => {
    if (!menus.has(menuId)) {
      menus.set(menuId, []);
    }

    const list = menus.get(menuId)!;
    const exists = list.some((existing) => existing.id === menuItem.id);
    if (!exists) {
      list.push(menuItem);
    }
  },
  getMenu: (menuId: string, context: WhenContext) => {
    const menuItems = menus.get(menuId) || [];
    menuItems.forEach(
      (item) => (item.disabled = item.whenDisabled?.(context) ?? false)
    );
    return menuItems.filter((item) => !item.when || item.when(context));
  },
};

export default MenuRegistry;
